package com.wt.struggle.goodbye.user.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.util.Log
import android.view.KeyEvent
import android.view.View
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ProActivity
import com.wt.struggle.goodbye.base.Send
import com.wt.struggle.goodbye.base.Share
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.wt.struggle.goodbye.view.CustomPop
import com.xin.lv.yang.utils.utils.ImageUtil
import kotlinx.android.synthetic.main.edit_user_info_layout.*
import kotlinx.android.synthetic.main.head.*
import org.devio.takephoto.app.TakePhoto
import org.devio.takephoto.model.CropOptions
import org.devio.takephoto.model.TResult
import org.json.JSONObject
import java.io.File


/**
 * 更新用户信息
 */
class EditUserInfoActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

        when (what) {
            Send.UPLOAD_PIC -> {
                removeLoadDialog()

                if (netInfo.code == Config.SUCCESS) {

                    val jsonObject = JSONObject(netInfo.dataResult)

                    if (jsonObject != null) {

                        resultPicId = jsonObject.optInt("id")
                        ImageUtil.getInstance().loadCircleImage(this, imageHead, chooseFile!!.absolutePath, 0)

                    }
                }
            }

            Send.UPDATE_USER_CODE -> {
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort("修改成功")
                    finish()
                }
            }
        }

    }

    var takeP: TakePhoto? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.edit_user_info_layout)
        tvTitle.text = "修改用户信息"
        tvRight.text = ""
        tvRight.visibility = View.GONE
        val userInfo = intent.getParcelableExtra<ProUserInfo>("userInfo")
        showUserInfo(userInfo)
        takeP = takePhoto

        imageBack.setOnClickListener {

            if (locationManager != null) {
                locationManager!!.removeUpdates(locationListener)

                locationManager = null
                locationListener = null
            }

            finish()
        }

        headLinear.setOnClickListener {
            openChoose()
        }

        btSaveUserInfo.setOnClickListener {
            save()
        }

        tvRight.setOnClickListener {
            val intent = Intent(this, RealNameActivity::class.java)
            intent.putExtra("userInfo", userInfo)
            startActivity(intent)
        }

        if (isLocationEnabled(this)) {
            getLocation()
        } else {
            showLocation()
        }

    }


    /**
     * 显示去打开位置服务
     */
    private fun showLocation() {
        val dialog = AlertDialog.Builder(this)
        dialog.setMessage("是否去设置打开位置服务?")
            .setPositiveButton("确定") { dd, i ->
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                startActivityForResult(intent, 6666)
                dd.dismiss()
            }.setNegativeButton("取消") { _, _ ->

            }.show()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 6666) {
            getLocation()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK && event!!.action == KeyEvent.ACTION_DOWN) {
            if (locationManager != null) {
                locationManager!!.removeUpdates(locationListener)
                locationManager = null
                locationListener = null
            }
        }

        return super.onKeyDown(keyCode, event)

    }


    /**
     * 开始定位
     */
    fun getLocation() {
        val code = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val code2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

        if (code == PackageManager.PERMISSION_GRANTED && code2 == PackageManager.PERMISSION_GRANTED) {

            get()

        } else {

            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
                5678
            )
        }
    }


    var location: Location? = null
    var addressStr: String = ""

    var locationManager: LocationManager? = null

    @SuppressLint("MissingPermission")

    fun get() {

        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

        val locationProvider = LocationManager.NETWORK_PROVIDER
        // 获取Location
        location = locationManager!!.getLastKnownLocation(locationProvider)

        /// 监视地理位置变化
        locationManager!!.requestLocationUpdates(locationProvider, 5000, 1f, locationListener)
    }


    var locationListener: LocationListener? = object : LocationListener {
        override fun onLocationChanged(p0: Location?) {
            this@EditUserInfoActivity.location = p0

            val geocoder = Geocoder(this@EditUserInfoActivity)

            val arr = geocoder.getFromLocation(location!!.latitude, location!!.longitude, 1);

            val address = arr[0]

            addressStr = address.featureName

        }

        override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {

        }

        override fun onProviderEnabled(p0: String?) {

        }

        override fun onProviderDisabled(p0: String?) {

        }
    }

    private fun showUserInfo(userInfo: ProUserInfo?) {
        ImageUtil.getInstance()
            .loadCircleImage(this, imageHead, Config.GET_IMAGE_URL + userInfo!!.avatar, R.mipmap.logo_small)
        etNickName.setText(userInfo.nickName)

    }

    private fun save() {
        val user = ProUserInfo()
        user.avatar = resultPicId
        user.nickName = etNickName.text.toString()
        user.realName = etNickName.text.toString()
        user.address = addressStr

        if (location != null) {
            user.lng = location!!.longitude.toString()
            user.lat = location!!.latitude.toString()
        }

        send!!.updateUserInfo(user, handler!!)
        showLoadDialog("修改中")
    }

    private fun openChoose() {
        val choosePop = CustomPop(this, 1)
        setAlpha(0.6f)
        choosePop.show(object : CustomPop.OnCheckListener {
            override fun onCamera() {
                if (choosePop.checkCameraPremission()) {

                    takeP!!.onPickFromCaptureWithCrop(buildUri(), buildOption())

                } else {
                    choosePop.checkCamera(this@EditUserInfoActivity)
                }

                setAlpha(1f)
                choosePop.dismiss()

            }


            override fun onPhoto() {

                if (choosePop.checkPhotoPremission()) {

                    takeP!!.onPickFromGalleryWithCrop(buildUri(), buildOption())

                } else {
                    choosePop.checkPhoto(this@EditUserInfoActivity)
                }

                setAlpha(1f)
                choosePop.dismiss()

            }

            override fun onClose() {
                setAlpha(1f)
            }

        })
    }

    private fun buildOption(): CropOptions? {
        return CropOptions.Builder().setWithOwnCrop(true).setOutputX(200).setOutputY(200).create()

    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            CustomPop.CAMERA_PERMISSION_CODE -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    takeP!!.onPickFromCaptureWithCrop(buildUri(), buildOption())

                }
            }

            CustomPop.PHOTO_PERMISSION_CODE -> {

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takeP!!.onPickFromGalleryWithCrop(buildUri(), buildOption())
                }
            }

            5678 -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED
                ) {

                    get()

                }
            }
        }
    }

    var chooseFile: File? = null
    var resultPicId = 0


    override fun takeSuccess(result: TResult?) {
        super.takeSuccess(result)

        val arrInfo = result!!.image

        Log.i("result", "---------------------------------" + arrInfo.originalPath)

        if (arrInfo != null) {

            chooseFile = File(arrInfo.originalPath)

            Log.i("result", "-------" + chooseFile!!.absoluteFile)

            if (chooseFile!!.exists()) {
                send!!.upImagePic(chooseFile!!.absolutePath, Share.getId(this).toString(), handler!!)
                showLoadDialog("上传中")
            }
        }

    }


}